<?php
/**
 * 数据导入
 * @author jianhui
 *
 */
class Import extends MY_Controller{
    var $navbar = array();
    function Import(){
        parent::MY_Controller();
        if (!$this->auth->isImport()){
            showError('您无此页面操作权限','/login_out.php');
        }
        $this->load->model('sellpointModel');
        $this->load->model('importMoneyModel');
        //面包屑
        $this->viewData['breadcrumb'][] = array('url'=>printUrl('Import', 'index'),'title'=>'数据导入');
        //标签菜单
        $this->navbar = array(
            array('title'=>'首页','url'=>printUrl('Import','index'),'focusTag'=>'index'),
            array('title'=>'广宣传播广宣形式管理','url'=>printUrl('Import','carLevel', array('type'=>3)),'focusTag'=>'carLevel3'),
            /* array('title'=>'营销活动形式管理','url'=>printUrl('Import','carLevel', array('type'=>4)),'focusTag'=>'carLevel4'), */
            array('title'=>'车展级别管理','url'=>printUrl('Import','carLevel', array('type'=>1)),'focusTag'=>'carLevel1'),
            array('title'=>'巡展类别管理','url'=>printUrl('Import','carLevel', array('type'=>2)),'focusTag'=>'carLevel2'),
            array('title'=>'专营店营销基金项目补贴上限额度','url'=>printUrl('Import','commonProjectFixed'),'focusTag'=>'commonProjectFixed'),
            array('title'=>'专营店营销基金-全年营销费用','url'=>printUrl('Import','importList',array('type'=>11)),'focusTag'=>'importList11'),
            array('title'=>'专营店营销基金-最终结算金额','url'=>printUrl('Import','importList',array('type'=>12)),'focusTag'=>'importList12'),
            array('title'=>'区域营销基金-双月额度','url'=>printUrl('Import','importList',array('type'=>21)),'focusTag'=>'importList21'),
            array('title'=>'车展基金-双月额度','url'=>printUrl('Import','importList',array('type'=>31)),'focusTag'=>'importList31'),
            array('title'=>'巡展基金-双月额度','url'=>printUrl('Import','importList',array('type'=>41)),'focusTag'=>'importList41'),
            array('title'=>'专项基金-双月额度','url'=>printUrl('Import','importList',array('type'=>51)),'focusTag'=>'importList51'),
        );
        $this->viewData['focusTag'] = $this->input->get('m');
    }
    /**
     * 列表
     */
    function index(){
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $this->viewData['year'] = $year;
        $this->load->view('Import/index', $this->viewData);
    }
    /**
     * 导入金额列表
     */
    function importList(){
        $type = (int)$this->input->get('type');
        $type || $type = 1;
        $this->viewData['type'] = $type;
        $where = array('type'=>$type);
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $where['year'] = $year;
        $this->viewData['year'] = $year;
        //时间段
        $timeUnit = (int)$this->input->get('timeUnit');
        $timeUnit && $where['timeUnit'] = $timeUnit;;
        $this->viewData['timeUnit'] = $timeUnit;
        //关键字
        $keyword = $this->input->get('keyword');
        $keyword && $where['storeName'] = array('like',$keyword);
        $this->viewData['keyword'] = $keyword;
        //载入模型
        $count = $this->importMoneyModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl('Import', 'commonFixed', $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        $this->viewData['list'] = $this->importMoneyModel->getNewList($where, $limit, $page, '', 'id desc');
        //设置选中标签
        $this->viewData['focusTag'] = $this->input->get('m').$this->input->get('type');
        $this->viewData['typeName'] = $this->importMoneyModel->getTypeName($type);
        $this->load->view('Import/importList', $this->viewData);
    }
    /**
     * 单店自主双月额度导入
     * @return boolean
     */
    function importAdd(){
        if ($_POST){
            $year = (int)$this->input->post('year');
            $year || showError('请选择年份');
            $type = (int)$this->input->post('type');
            $type || showError('请选择类型');
            $timeUnit = 0;
            if (!in_array($type, array(51))){//固定传播基金
                $timeUnit = (int)$this->input->post('timeUnit');
                $timeUnit || showError('请选择双月');
            }
            //上传文件
            $fileData = $this->upload();
            $fullPath = $fileData['full_path'];
            $handle = fopen ($fullPath, "r");
            $i = 0; $ok = 0; $err = 0;
            $errorSellpoint = array();
            //载入专营店营销基金主线流程模型
            $this->load->model('commonProcessModel');
            $this->load->model('areaProcessModel');
            $this->load->model('carProcessModel');
            $this->load->model('xunProcessModel');
            $this->load->model('specialProcessModel');
            while ($item = fgetcsv($handle, 10000, ",")){
                if($i==0){$i++;continue;}//跳过第一行
                $coding = $item[5];
                $storeData = $this->sellpointModel->getNewData(array('Coding'=>$coding, 'SpState_sys'=>1,'isOpen'=>1));
                if (!$storeData){
                    $err ++;
                    $errorSellpoint[] = "【".gbk2utf8($item[4])."】的编码【".$coding."】错误";
                    continue;
                }
                $where = array(
                    'storeId' => (int)$storeData['userId'],
                    'timeUnit' => (int)$timeUnit,
                    'year' => (int)$year,
                    'type' => $type,
                );
                $data = array(
                    'area' => $storeData['area'],
                    'region' => $storeData['region'],
                    'spsarea' => $storeData['spsarea'],
                    'city' => $storeData['city'],
                    'coding' => $storeData['coding'],
                    'storeName' => $storeData['storeName'],
                    'money' => (float)$item[6],
                    'createTime' => time()
                );
                if ($this->importMoneyModel->upset($where, $data)){
                    $ok ++;
                    //后续处理
                    switch ($type){
                        case 11://专营店活动营销基金--全年营销费用
                        case 12://专营店营销基金-最终结算金额
                            //生成主线流程数据并更新固定额度
                            $procId = $this->commonProcessModel->initData(array('storeId'=>$where['storeId'], 'year'=>$where['year'],'timeUnit'=>$where['timeUnit']));
                            $this->commonProcessModel->updateMoney($procId);
                            break;
                        case 21://区域营销基金-双月额度
                            //生成主线流程数据并更新固定额度
                            $procId = $this->areaProcessModel->initData(array('storeId'=>$where['storeId'], 'year'=>$where['year'],'timeUnit'=>$where['timeUnit']));
                            $this->areaProcessModel->updateMoney($procId);
                            break;
                        case 31://车展基金-双月额度
                            //生成主线流程数据并更新固定额度
                            $procId = $this->carProcessModel->initData(array('storeId'=>$where['storeId'], 'year'=>$where['year'],'timeUnit'=>$where['timeUnit']));
                            $this->carProcessModel->updateMoney($procId);
                            break;
                        case 41://巡展基金-双月额度
                            //生成主线流程数据并更新固定额度
                            $procId = $this->xunProcessModel->initData(array('storeId'=>$where['storeId'], 'year'=>$where['year'],'timeUnit'=>$where['timeUnit']));
                            $this->xunProcessModel->updateMoney($procId);
                            break;
                        case 51://专项基金-双月额度
                            //生成主线流程数据并更新固定额度
                            $procId = $this->specialProcessModel->initData(array('storeId'=>$where['storeId'], 'year'=>$where['year'],'timeUnit'=>$where['timeUnit']));
                            $this->specialProcessModel->updateMoney($procId);
                            break;
                        default:
                    }
                }else{
                    $err ++;
                }
                usleep(500);
            }
            showSuccess('导入完成：（成功条数：'.$ok.',失败条数：'.$err.'）'.($errorSellpoint ? "<br>".implode('<br>',$errorSellpoint):''), '', $errorSellpoint?120:3);
        }else{
            //年
            $year = $this->input->get('year');
            $year || $year = $this->config->item('nowYear');
            $this->viewData['year'] = $year;
            $type  = (int)$this->input->get('type');
            $type || showError('请选择导入类型');
            $this->viewData['type'] = $type;
            $this->viewData['typeName'] = $this->importMoneyModel->getTypeName($type);
            $templateFile = array(
                11 => 'commenMarket.zip',
                12 => 'commenFinalSettle.zip',
                21 => 'areaFixed.zip',
                31 => 'carFixed.zip',
                41 => 'xunFixed.zip',
                51 => 'specialFixed.zip',
            );
            $this->viewData['templateFile'] = isset($templateFile[$type]) ? 'public/template/'.$templateFile[$type] : '';
            $this->load->view('Import/importAdd', $this->viewData);
        }
    }
    /**
     * 专营店营销基金-项目补贴上限额度列表
     */
    function commonProjectFixed(){
        $where = array();
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $where['year'] = $year;
        $this->viewData['year'] = $year;
        //关键字
        $keyword = $this->input->get('keyword');
        $keyword && $where['city'] = $keyword;
        $this->viewData['keyword'] = $keyword;
        //载入模型
        $this->load->model('commonPFixedModel');
        $count = $this->commonPFixedModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl($_GET['c'], $_GET['m'], $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        $this->viewData['list'] = $this->commonPFixedModel->getNewList($where, $limit, $page, '', 'id desc');
    
        $this->load->view('Import/commonProjectFixed', $this->viewData);
    }
    /**
     * 专营店营销基金-项目补贴上限额度导入
     * @return boolean
     */
    function commonProjectFixedAdd(){
        if ($_POST){
            $year = (int)$this->input->post('year');
            $year || showError('请选择年份');
            //上传文件
            $fileData = $this->upload();
            $fullPath = $fileData['full_path'];
            $handle = fopen ($fullPath, "r");
            $i = 0; $ok = 0; $err = 0;
            $errorSellpoint = array();
            //载入单店主线流程模型
            $this->load->model('commonPFixedModel');
            while ($item = fgetcsv($handle, 10000, ",")){
                if($i==0){$i++;continue;}//跳过第一行
                $where = array(
                    'year' => (int)$year,
                    'city' => trim(gbk2utf8($item[1])),
                );
                $data = array(
                    'systemCity'    => trim(gbk2utf8($item[1])),
                    'cityLevel'     => (int)$item[3],
                    'createTime'    => time()
                );
                $moneyData = array(
                    'money1' => (float)$item[4],//店头活动
                    'money2' => (float)$item[5],//新车上市活动
                    'money3' => (float)$item[6],//试驾活动
                    'money4' => (float)$item[7],//保客活动
                    'money5' => (float)$item[8],//外租场地团购会
                    'money6' => (float)$item[9],//商超展示
                    'money7' => (float)$item[10],//外展
                    'money8' => (float)$item[11],//二网巡展
                    'money9' => (float)$item[12],//车展外场支持
                    'money10' => (float)$item[13],//非年度车展站点
                    'money11' => (float)$item[14],//小篷车巡展
                );
                $data['moneyData'] = serialize($moneyData);
                if ($this->commonPFixedModel->upset($where, $data)){
                    $ok ++;
                }else{
                    $err ++;
                }
                usleep(500);
            }
            showSuccess('导入完成：（成功条数：'.$ok.',失败条数：'.$err.'）', '', 3);
        }else{
            //年
            $year = $this->input->get('year');
            $year || $year = $this->config->item('nowYear');
            $this->viewData['year'] = $year;
            $this->load->view('Import/commonProjectFixedAdd', $this->viewData);
        }
    }
    /**
     * 车展级别或巡展类别管理
     */
    function carLevel(){
        $where = array();
        //类别
        $type = $this->input->get('type');
        $type || $type = 1;
        $where['type'] = $type;
        $this->viewData['type'] = $type;
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $where['year'] = $year;
        $this->viewData['year'] = $year;
        //时间单位
        $timeUnit = (int)$this->input->get('timeUnit');
        $timeUnit && $where['timeUnit'] = $timeUnit;
        $this->viewData['timeUnit'] = $timeUnit;
        //载入模型
        $this->load->model('carLevelModel');
        $count = $this->carLevelModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl($_GET['c'], $_GET['m'], $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        $this->viewData['list'] = $this->carLevelModel->getNewList($where, $limit, $page, '', 'orderNum asc,id asc');
        //设置选中标签
        $this->viewData['focusTag'] = $this->input->get('m').$type;
        $this->viewData['typeName'] = $this->carLevelModel->getTypeName($type);
        $this->load->view('Import/carLevel', $this->viewData);
    }
    /**
     * 车展级别或巡展级别添加或修改
     */
    function carLevelAdd(){
        $this->load->model('carLevelModel');
        if ($_POST){
            $id = (int)$this->input->post('id');
            $where = array(
                'year'      => $this->input->post('year'),
                'timeUnit'  => (int)$this->input->post('timeUnit'),
                'name'      => $this->input->post('name'),
                'type'      => (int)$this->input->post('type'),
            );
            $data = array(
                'orderNum'  => (int)$this->input->post('orderNum'),
            );
            $where['year'] || showError('请选择年份');
            $where['timeUnit'] || showError('请选择双月');
            $where['type'] || showError('请选择类别');
            $where['name'] || showError('名称不能为空');
            if (!$id && $this->carLevelModel->getData($where)){
                showError('您已经添加过同名数据');
            }
            if ($id){
                if ($this->carLevelModel->edit($id, array_merge($where, $data))){
                    //更新缓存
                    $this->carLevelModel->createActionCache();
                    showSuccess('编辑成功');
                }else{
                    showError('编辑失败');
                }
            }else{
                $data['status'] = 1;
                $data['createTime'] = time();
                if ($this->carLevelModel->add(array_merge($where, $data))){
                    //更新缓存
                    $this->carLevelModel->createActionCache();
                    showSuccess('添加成功');
                }else{
                    showError('添加失败');
                }
            }
        }else{
            //类别
            $type = $this->input->get('type');
            $type || $type = 1;
            $id = (int)$this->input->get('id');
            if ($id){
                $findData = $this->carLevelModel->getData($id);
                $type = $findData['type'];
                $this->viewData['data'] = $findData;
                $this->viewData['year'] = $findData['year'];
                $this->viewData['timeUnit'] = $findData['timeUnit'];
            }else{
                $this->viewData['year'] = $this->config->item('nowYear');
                $this->viewData['timeUnit'] = $this->timeUnitModel->getNowTimeUnit();
            }
            //类型名称
            $this->viewData['type'] = $type;
            $this->viewData['typeName'] = $this->carLevelModel->getTypeName($type);
            
            $this->load->view('Import/carLevelAdd', $this->viewData);
        }
    }
    /**
     * 级别状态
     */
    function carLevelStatus(){
        $where['id'] = (int)$this->input->post('id');
        $where['id'] || showError('请选择要操作的数据');
        $this->load->model('carLevelModel');
        $findData = $this->carLevelModel->getData($where);
        $data = array(
            'status' => $findData['status'] == 1 ? 0 : 1,
        );
        if ($this->carLevelModel->edit($where, $data)){
            //更新缓存
            $this->carLevelModel->createActionCache();
            showSuccess('更改状态成功');
        }else{
            showError('更改状态失败');
        }
    }
    /**
     * 上传文件
     * @return array
     */
    function upload(){
        //允许上传文件格式
        $config['allowed_types'] = 'csv';
        $extPath = date('Ymd');//子目录
        //上传目录
        $config['upload_path'] = '../upload/'. $extPath .'/';
        //网站目录
        $webPath = substr($config['upload_path'], 2);
        //判断上传目录是否存在，不存在则创建
        if (!is_dir($config['upload_path'])){
            mkdir($config['upload_path'],0777);
        }
        //是否重命名
        $config['encrypt_name'] = TRUE;
        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload('inputFile'))
        {
            $error = $this->upload->display_errors('','');
            showError($error);
        } else {
            $data = $this->upload->data();
            return $data;
        }
    }
}